﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KinectServer.Util;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace KinectServer.Module
{
    public class FrameServer : UdpServer
    {
        private AsyncFrameBuffer _colorBuffer;
        private AsyncFrameBuffer _depthBuffer;
       
        private MemoryStream encodedColorBuffer = new MemoryStream();
        private MemoryStream encodedDepthBuffer = new MemoryStream();

        public FrameServer()
        {
            _colorBuffer = ((App)App.Current).ColorBuffer;
            _depthBuffer = ((App)App.Current).DepthBuffer;
        }

        protected override MemoryStream OnGetColorData()
        {
            GetFrame("C", _colorBuffer, encodedColorBuffer);
            return encodedColorBuffer;
        }

        protected override MemoryStream OnGetDepthData()
        {
            GetFrame("D", _depthBuffer, encodedDepthBuffer);
            return encodedDepthBuffer;
        }

        private static void GetFrame(String type, AsyncFrameBuffer rawBuffer, MemoryStream encodedBuffer)
        {
            MemoryStream bitmapStream = rawBuffer.Bits;

            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.QualityLevel = 70;
            encoder.Frames.Clear();
            BitmapSource src = BitmapSource.Create(rawBuffer.Width, rawBuffer.Height, rawBuffer.DpiX, rawBuffer.DpiY, rawBuffer.PixelFormat, null, rawBuffer.Bits.ToArray(), rawBuffer.Stride);
            encoder.Frames.Add(BitmapFrame.Create(src));

            //Write Data Packet
            encodedBuffer.Position = 0;

            //Header
            byte[] header = ASCIIEncoding.Default.GetBytes(type);
            encodedBuffer.Write(header, 0, header.Length);

            //Content
            encoder.Save(encodedBuffer);
        }
     
    }
}
